package com.study.webapp.jdk8;

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Semaphore;

/**
 * @program: study
 *
 * @description:
 *
 * @author: heqiang
 *
 * @create: 2020-05-06 14:18
 **/
public class SemaphoreTest {

    public static void main(String[] args) throws Exception {
        Semaphore semaphore = new Semaphore(3,true);
        for (int i = 1; i<=6; i++) {
            Thread t = new Thread(new Person("第"+i+"人",semaphore));
            t.start();
            Thread.sleep(new Random().nextInt(300));
        }
    }



    static class Person implements Runnable {

        private String name;
        private Semaphore semaphore;

        public Person (String name,Semaphore semaphore) {
            this.name = name;
            this.semaphore = semaphore;
        }

        @Override
        public void run() {
            System.out.println(name + "等待中。。。。。");
            if (semaphore.availablePermits() > 0) {
                System.out.println(name + ":有位子，哈哈哈");
            } else {
                System.out.println(name + "还没位子，继续等");
            }
            try {
                //申请位子
                semaphore.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(name + ":终于申请到位子了");
            try {
                //模拟线程占用时间
                Thread.sleep(new Random().nextInt(1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(name + ":我使用好了，可以下一位了");
            semaphore.release();
        }
    }
}
